export default {
    getUrlByCfg(cfg: any = null, type: any = 0) {
        if (cfg?.url) {
            return cfg.url;
        } else if (cfg?.port) {
            return (
                (type
                    ? window.location.protocol.includes('s')
                        ? 'wss:'
                        : 'ws:'
                    : window.location.protocol) +
                '//' +
                window.location.hostname +
                ':' +
                cfg.port
            );
        } else {
            return type
                ? window.location.origin.replace('http', 'ws')
                : window.location.origin;
        }
    },
    arrLenMax(arr: any[], lenmax: number, type: number = 0) {
        if (arr.length > lenmax) {
            if (type) {
                arr.splice(lenmax, arr.length - lenmax);
            } else {
                arr.splice(0, arr.length - lenmax);
            }
        }
        return arr;
    },
    setCookies(key: string, val: any, expires: number = 0, path: string = '/') {
        let expiresStr: string = '';
        if (expires) {
            const date: any = new Date();
            date.setTime(date.getTime() + expires);
            expiresStr = '; expires=' + date.toUTCString();
        }
        document.cookie =
            key +
            '=' +
            encodeURIComponent(val) +
            expiresStr +
            '; path=' +
            (path || '/');
    },
    // cookies储存数据到本地缓存
    cookiesSet(
        key: string,
        val: string,
        expires: number = 0,
        path: string = '/'
    ) {
        try {
            let expiresStr: string = '';
            if (expires) {
                const date: any = new Date();
                date.setTime(date.getTime() + expires);
                expiresStr = '; expires=' + date.toUTCString();
            }
            document.cookie =
                key + '=' + val + expiresStr + '; path=' + (path || '/');
        } catch (err) {}
    },
    // cookies读取本地缓存数据
    cookiesGet(key: string) {
        try {
            const cookiesStr: string = document.cookie;
            let cStr: string = cookiesStr.substring(
                cookiesStr.indexOf(key + '=') + (key + '=').length
            );
            const eIndex: number = cStr.indexOf('; ');
            if (eIndex > -1) {
                return cStr.substring(0, eIndex);
            }
            return cStr;
        } catch (err) {}
        return '';
    },
    cookiesDel(key: string) {
        this.setCookies(key, '', -1000);
    },
    cookiesClear() {
        const cookies: any = document.cookie.split('; ');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i];
            const eqPos = cookie.indexOf('=');
            const tKeys: string =
                eqPos > -1 ? cookie.substring(0, eqPos) : cookie;
            document.cookie =
                tKeys + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
        }
    },
    readFile(file: any = null, ty: number = 0) {
        return new Promise((resolve: any, reject: any) => {
            if (file) {
                const reader: any = new FileReader();
                if (ty) {
                    reader.readAsText(file);
                } else {
                    reader.readAsDataURL(file);
                }
                reader.onload = () => {
                    resolve(reader.result);
                };
            } else {
                reject();
            }
        });
    },
    apiJsonp(url: string, callback: any) {
        try {
            let scriptHandler = document.createElement('script');
            scriptHandler.type = 'text/javascript';
            scriptHandler.innerHTML = `
      window.cbdata;
      function asaiJsonp(data) {
        cbdata=data;
      }`;
            document.body.appendChild(scriptHandler);
            let script = document.createElement('script');
            script.src = `${url}&&callback=asaiJsonp`;
            script.type = 'text/javascript';
            script.async = true;
            document.body.appendChild(script);
            script.onload = () => {
                document.body.removeChild(script);
                callback && callback((window as any)?.cbdata);
                document.body.removeChild(scriptHandler);
            };
        } catch (e) {
            callback && callback('ERROR');
        }
    },
    localTime(key: string, expires: number = 0) {
        if (expires) {
            const dataTime: any = JSON.parse(this.localGet('astime') || '{}');
            dataTime[key] = expires;
            localStorage.setItem('astime', JSON.stringify(dataTime));
        } else {
            const dataTime: any = JSON.parse(this.localGet('astime') || '{}');
            if (dataTime[key]) {
                return dataTime[key];
            }
        }
        return 0;
    },
    // 储存数据到本地缓存
    localSet(key: string, val: any, storageType: Storage = localStorage) {
        try {
            // this.localTime(key, expires);
            storageType.setItem(key, this.toStr(val));
        } catch (err) {}
    },
    // 读取本地缓存数据
    localGet(key: string, storageType: Storage = localStorage) {
        try {
            // const ltm: number = this.localTime(key) || 0;
            // const ctm: number = Date.now();
            // if (!ltm || ltm > ctm) {
            return storageType.getItem(key);
            // } else {
            //     storageType.removeItem(key);
            // }
        } catch (err) {}
        return '';
    },
    //清空本地缓存数据
    localRemove(key: string, storageType: Storage = localStorage) {
        try {
            return storageType.removeItem(key);
        } catch (err) {}
    },
    // 清空本地所有缓存数据
    localClears(keys: any = null, storageType: Storage = localStorage) {
        if (keys?.length) {
            let clKey: any;
            for (let item in storageType) {
                clKey = keys.find((el: string) => item.startsWith(el));
                if (clKey) {
                    this.localRemove(item, storageType);
                }
            }
        } else {
            this.localClear(storageType);
        }
    },
    // 清空本地所有缓存数据
    localClear(storageType: Storage = localStorage) {
        storageType.clear();
    },
    // 清空本地所有缓存并刷新界面
    localInit(storageType: Storage = localStorage) {
        this.localClear(storageType);
        location.replace('/#');
        this.localReload();
    },
    localReload() {
        location.reload();
    },
    getPath(str: string = '-') {
        return str?.replace(/[^a-zA-Z0-9.\-_\\\/]/g, '');
    },
    getName(str: string = '-') {
        return str?.replace(/[^a-zA-Z0-9.\-_]/g, '');
    },
    // 阻碍事件向上、向下传播
    eStop(e: any) {
        const _e: any = window.event || e;
        _e?.preventDefault();
        _e?.stopPropagation();
        return true;
    },
    // 全屏功能
    fullScreen(id: string = '') {
        const element: any = id
            ? document.getElementById(id)
            : document.documentElement || document.body;
        const requestMethod: any =
            element.requestFullScreen ||
            element.webkitRequestFullScreen ||
            element.mozRequestFullScreen ||
            element.msRequestFullScreen;
        if (requestMethod) {
            requestMethod.call(element);
        } else {
            const { ActiveXObject } = window as any;
            if (typeof ActiveXObject !== 'undefined') {
                const wscript = new ActiveXObject('WScript.Shell');
                if (wscript !== null) {
                    wscript.SendKeys('{F11}');
                }
            }
        }
    },
    // 退出全屏
    fullScreenExit() {
        const exitMethod: any = document?.exitFullscreen;
        // ||
        // document?.webkitExitFullScreen ||
        // document?.mozCancelFullScreen ||
        // document?.msExitFullScreen;
        if (exitMethod) {
            document.fullscreenElement !== null && exitMethod.call(document);
        } else {
            const { ActiveXObject } = window as any;
            if (typeof ActiveXObject !== 'undefined') {
                const wscript = new ActiveXObject('WScript.Shell');
                if (wscript !== null) {
                    wscript.SendKeys('{F11}');
                }
            }
        }
    },
    // 全屏
    fullScreenDo(callback: any = null) {
        if (document.fullscreenElement) {
            this.fullScreenExit();
        } else {
            this.fullScreen();
        }
        if (callback) {
            callback();
        }
    },
    toNums(obj: any, len: number = 0) {
        if (obj) {
            Object.keys(obj).forEach((el: string) => {
                if (typeof obj[el] === 'number') {
                    obj[el] = this.toNum(obj[el], len);
                }
            });
        }
        return obj;
    },
    toNum(num: any, len: number = 0) {
        if (typeof num !== 'number') {
            if (typeof num === 'string') {
                num = Number(num);
            }
        }
        if (Number.isNaN(num)) {
            num = 0;
        }
        if (num && len) {
            num = Math.round(num * 10 ** len) / 10 ** len;
        }
        return num;
    },
    // 将字符串转换为对象obj
    toObj(str: any) {
        try {
            if (str && typeof str === 'string') {
                return JSON.parse(str);
            }
            return str;
        } catch (e) {
            return { err: '不是JSON格式数据' };
        }
    },
    // 将对象转换为字符串
    toStr(obj: any) {
        if (typeof obj === 'string') {
            return obj;
        } else {
            try {
                return JSON.stringify(obj);
            } catch (err) {
                const cache: any = [];
                return JSON.stringify(obj, (_key: any, value: any) => {
                    if (typeof value === 'object' && value !== null) {
                        if (cache.indexOf(value) !== -1) {
                            return;
                        }
                        cache.push(value);
                    }
                    return value;
                });
            }
        }
    },
    // 获取当前时间
    getTime(type: number = 6, timenow: number = 0) {
        let tmpstr: string = '';
        let curDate: any;
        if (timenow) {
            // 特殊处理带小数点的数字转义时间
            if (timenow < 9999999999) {
                timenow = timenow * 1000;
            }
            curDate = new Date(timenow);
        } else {
            curDate = new Date();
        }

        const [a, b] = type > 9 ? type + '' : '0' + type;

        function ckType(nval: number) {
            return +a <= nval && +b >= nval;
        }

        ckType(1) && (tmpstr += ('00' + curDate.getFullYear()).slice(-4) + '-');
        ckType(2) &&
            (tmpstr += ('00' + (curDate.getMonth() + 1)).slice(-2) + '-');
        ckType(3) && (tmpstr += ('00' + curDate.getDate()).slice(-2) + ' ');
        ckType(4) && (tmpstr += ('00' + curDate.getHours()).slice(-2) + ':');
        ckType(5) && (tmpstr += ('00' + curDate.getMinutes()).slice(-2) + ':');
        ckType(6) && (tmpstr += ('00' + curDate.getSeconds()).slice(-2) + '.');
        ckType(7) &&
            (tmpstr += ('000' + curDate.getMilliseconds()).slice(-3) + ' ');

        if (ckType(9)) {
            return tmpstr.replace(/\D/g, '');
        } else if (tmpstr) {
            return tmpstr.substring(0, tmpstr.length - 1);
        }
        return tmpstr;
    },
    /**
     * 简化版
     * @param startsWord 定义起始字符，如：as
     * @param hex 指定进制，如：10 16 32
     * @returns 12位，前缀字符+时间戳换算+随机数补位，如：eelgullaqnb0
     */
    Uuid(startsWord: string = '', index: number = 0, hex: number = 32): string {
        const buffer = [
            Date.now().toString(36).slice(-9),
            index.toString(36),
            startsWord.slice(-3),
            crypto
                .getRandomValues(new Uint8Array(6))
                .reduce((acc, val) => acc + (val & 0x0f).toString(hex), ''),
        ];
        return buffer.join('').slice(0, 16);
    },
    // 下载txt数据到文件中
    downloadTxt(data: any = '', filename: string = '') {
        if (data) {
            if (typeof data === 'object') {
                data = JSON.stringify(data);
            }
            const elink = document.createElement('a');
            elink.style.display = 'none';

            const blob = new Blob([data], {
                type: 'application/octet-stream;charset=utf-8',
            });
            const url = URL.createObjectURL(blob);
            elink.href = url;

            // elink.href = 'data:text/plain;base64,' + pjData;
            // elink.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(data);
            // elink.href = 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(data);

            elink.setAttribute('download', filename);
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
            URL.revokeObjectURL(url);
        }
    },
    // 防抖：连续操作中，仅在数据持续一段时间不变时fn一次
    debounce(fn: any, opt: any) {
        if (opt?.timeout) {
            clearTimeout(opt.timeout);
            opt.timeout = null;
        }
        if (opt?.immediate) {
            // 立即执行一次，停留满wait时再执行
            if (!opt.timeout) {
                fn();
            }
            opt.timeout = setTimeout(() => {
                opt.timeout = null;
            }, opt.wait);
        } else {
            // 停留满wait时后执行一次
            opt.timeout = setTimeout(() => {
                fn();
                clearTimeout(opt.timeout);
                opt.timeout = null;
            }, opt.wait);
        }
    },
    // 节流:固定长度时间内只能fn一次
    throttle(fn: any, opt: any) {
        if (opt?.timeout) {
            clearTimeout(opt.timeout);
            opt.timeout = null;
        }
        if (opt?.immediate) {
            // 立即执行一次，然后一段时间的结束位执行一次，未达结束位不执行
            opt.endtime = new Date().valueOf();
            if (opt.endtime - opt.starttime > opt.wait) {
                fn();
                opt.starttime = opt.endtime;
            }
        } else {
            if (opt && !opt?.timeout) {
                // 一段时间的开始位延后wait执行一次，结束位不执行
                opt.timeout = setTimeout(() => {
                    fn();
                    clearTimeout(opt.timeout);
                    opt.timeout = null;
                }, opt.wait);
            }
        }
    },
    /**
     * 复制文本到剪贴板（兼容新旧 API）
     * @param text 要复制的文本
     * @returns 成功返回 true，失败返回 false
     */
    async copyToClipboard(text: string): Promise<boolean> {
        try {
            // 首选方法：使用现代异步 Clipboard API
            // if (navigator.clipboard && window.isSecureContext) {
            //     await navigator.clipboard.writeText(text);
            //     // console.log('复制成功（现代 API）');
            //     return true;
            // }
            this.localSet('as-clipboard', text);
            return true;
        } catch (error) {
            throw error;
        }
    },
    /**
     * 从剪贴板读取文本（兼容处理）
     * @returns 成功返回文本内容，失败返回 null 或错误信息
     */
    async readFromClipboard(): Promise<string | null> {
        try {
            // if (navigator.clipboard?.readText) {
            //     return await navigator.clipboard.readText();
            // }
            return this.localGet('as-clipboard') || '';
        } catch (error) {
            throw error;
        }
    },
};
